Let's create a Date
object in different ways:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
// Current Date and Time
let currentDate = new Date();
console.log("Current Date and Time: " + currentDate);
// Using a String
let dateString = new Date("December 17, 2023 03:24:00");
console.log("Date from String: " + dateString);
// Using Year, Month, Day, Hour, Minute, Second
let specificDate = new Date(2023, 11, 17, 3, 24, 0); // Note: Months are zero-based (0-11)
console.log("Specific Date: " + specificDate);
</Script>
</body>
</html>
Some methods to retrieve and manipulate date information:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
// Get components of the current date
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1; // Months are zero-based
let day = date.getDate();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
console.log(`Year: ${year}, Month: ${month}, Day: ${day}, Hours: ${hours}, Minutes: ${minutes}, Seconds: ${seconds}`);
// Format Date
let formattedDate = date.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
console.log("Formatted Date: " + formattedDate);
// Date Arithmetic
let futureDate = new Date(date.getTime() + 7 * 24 * 60 * 60 * 1000); // Adding 7 days
console.log("Future Date: " + futureDate);
</Script>
</body>
</html>
Click the button below to see the current date and time: